package com.ideafactory.client.ybservice;

import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteException;
import android.speech.tts.TextToSpeech;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
//import com.gprinter.aidl.GpService;
import com.gprinter.command.GpCom;
import com.gprinter.io.GpDevice;
import com.gprinter.service.GpPrintService;
import com.ideafactory.client.afinal.NetConstants;
import com.ideafactory.client.beans.BusSelfService;
import com.ideafactory.client.beans.OrderBaseInfoBean;
import com.ideafactory.client.beans.OrderGoodsBean;
import com.ideafactory.client.beans.StoreBean;
import com.ideafactory.client.br.PayingBroadcast;
import com.ideafactory.client.print.Constant;
import com.ideafactory.client.print.T;
import com.ideafactory.client.print.Utils;
import com.ideafactory.client.print.icod.IcodPrinterManager;
import com.ideafactory.client.utils.FileConstants;

import com.ideafactory.client.utils.HandleMessageUtils;
import com.ideafactory.client.utils.HeartBeatClient;
import com.ideafactory.client.utils.JsonForBean;
import com.ideafactory.client.utils.SoundControl;
import com.ideafactory.client.utils.SpUtils;
import com.ideafactory.client.utils.caches.CacheUtils;
import com.ideafactory.client.utils.netutils.MyCallBack;
import com.ideafactory.client.utils.netutils.NetUtils;
import com.ideafactory.client.utils.power.PowerOffTool;
import com.ideafactory.client.views.MenuToShow;
import com.ideafactory.client.xmpp.Constants;
import com.ideafactory.client.xmpp.ServiceManager;
import com.ideafactory.client.ybselfservice.R;
import com.ideafactory.client.ybservice.ybviewpager.GoodsBasePager;
import com.printsdk.cmd.PrintCmd;
import com.printsdk.usbsdk.UsbDriver;

import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;




public class YbSelfService extends FragmentActivity {
    private static final String TAG = "YbSelfService";

    private MyViewPager ivmain_view_pager;


    private ImageView iv_mainBg;
    private TextView tv_no;


    private List<YbBaseFragment> fragmentList;
    private MyFrageStatePagerAdapter adapter;

    public static final int mainPosition = 0;
    public static final int detialPosition = 1;



    private APP appContent;
    private static HashMap testSpeechMap;//科大讯飞设置
    private PayingBroadcast myPayingBroadcast;//付款的广播



    // 打印工具
    private int state;
    public static UsbDriver mUsbDriver;
    private UsbManager mUsbManager;
    private static final String ACTION_USB_PERMISSION =  "com.usb.sample.USB_PERMISSION";
    private boolean shareFlag = false;
    private int clickFlag = 1; // 1：BMP；0：IMG
    private final static int PID11 = 8211;
    private final static int PID13 = 8213;
    private final static int PID15 = 8215;
    private final static int VENDORID = 1305;
    private int densityValue = 80; // 默认：80,浓度范围：70-200
    public static UsbDevice mUsbDev1;		//打印机1
    public static UsbDevice mUsbDev2;		//打印机2

    //wifi打印机
    public PrinterServiceConnection conn = null;
//    public static GpService mGpService = null;
    private static final int MAIN_QUERY_PRINTER_STATUS = 0xfe;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_yb_self_service);
          ivmain_view_pager= (MyViewPager) findViewById(R.id.ivmain_view_pager);
        iv_mainBg= (ImageView) findViewById(R.id.iv_mainBg);
        tv_no= (TextView) findViewById(R.id.tv_no);
        appContent = APP.getAPP();
        AppActivityManager.getAppActivityManager().addActivity(this);
        initUtils();
        initViewPager();
        HandleMessageUtils.getInstance().runInThread(costTime);//设置开关机


        HeartBeatClient.getInstance().setMainActivity(this);

        startXmpp();//开启Xmpp
        initReceiver();//初始化UI
        initData();
        registerInternetReceiver();

        //小票打印机
        initTicketPrenter();
        initIcodPrinter();
//        //wifi打印机
//        registerBroadcast();
//        connection();
        tv_no.setText( CacheUtils.getSerNumber());
//        new Handler().postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                tv_no.setText( CacheUtils.getSerNumber());
//            }
//        },8000);
    }

    private void initIcodPrinter() {
        IcodPrinterManager.getIns().connect();
    }
    private void initTicketPrenter() {
        mUsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
        mUsbDriver = new UsbDriver(mUsbManager, this);
        PendingIntent permissionIntent1 = PendingIntent.getBroadcast(this, 0,
                new Intent(ACTION_USB_PERMISSION), 0);
        mUsbDriver.setPermissionIntent(permissionIntent1);

        // Broadcast listen for new devices
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
        registerReceiver(mUsbReceiver, filter);

    }

    private void initUtils() {
        mTextToSpeech = new TextToSpeech(YbSelfService.this, new TextToSpeech.OnInitListener() {
            @Override
            public void onInit(int status) {
                if (status == TextToSpeech.SUCCESS) {
                    // 设置朗读语言
                    Locale locale = getResources().getConfiguration().locale;
                    // 设置朗读语言
                    int supported = mTextToSpeech
                            .setLanguage(locale);
                    if ((supported != TextToSpeech.LANG_AVAILABLE)
                            && (supported != TextToSpeech.LANG_COUNTRY_AVAILABLE)) {
                        AlertDialog.Builder builder = new AlertDialog.Builder(YbSelfService.this);
                        builder.setMessage("请设置支持中文语音");
                        builder.setTitle("警告");
                        AlertDialog dialog= builder.create();
                        if (dialog!=null&&!dialog.isShowing()){
                            dialog .show();
                        }

                    }
                }
            }
        });

        testSpeechMap = new HashMap();
        testSpeechMap.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "abcdefg");
        testSpeechMap.put(TextToSpeech.Engine.KEY_PARAM_STREAM, String.valueOf(AudioManager.STREAM_RING));

        myPayingBroadcast = new PayingBroadcast();
        registerReceiver(myPayingBroadcast, new IntentFilter(Constants.PAYING));

    }

    private void initViewPager() {//初始化UI
        fragmentList = new ArrayList<>();
        fragmentList.add(new MainFragment());
        fragmentList.add(new YbDetialFragment());
        adapter = new MyFrageStatePagerAdapter(getSupportFragmentManager());
        adapter.setFragmentList(fragmentList);
        ivmain_view_pager.setScanScroll(false);
    }


    private void initReceiver() {//设置点击切换界面
        setToNextPager(new OnToNext() {
            @Override
            public void toNext(int position) {
                System.gc();
                if(!printConnStatus()){
                }
                ivmain_view_pager.setCurrentItem(position, false);
            }
        });
    }

    private Runnable costTime = new Runnable() {
        @Override
        public void run() {
            //开关机
            PowerOffTool.machineStart();

        }
    };

    private ConnectionChangeReceiver myReceiver;//网络监听器

    private  void registerInternetReceiver(){
        IntentFilter filter1=new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
        myReceiver=new ConnectionChangeReceiver();

        try {
            registerReceiver(myReceiver, filter1);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private  class ConnectionChangeReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                ConnectivityManager connectivityManager=(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
                NetworkInfo wifiNetInfo=connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
                if ( !wifiNetInfo.isConnected()) {
                    Log.e(TAG, "onReceive: 网络不可用 ");
                }else {
                    Log.e(TAG, "onReceive: 网络可用！！！！！！ ");
                    initData();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void initData() {

        String deviceNo =  SpUtils.getString(APP.getAPP(), SpUtils.DEVICENO, "");
        Log.e("设备编码",deviceNo);
        final HashMap map = new HashMap();
        map.put("deviceNo", deviceNo);
        NetUtils.Post(NetConstants.SERVICE_BASE_INFO, map, new MyCallBack<String>() {
            @Override
            public void onSuccess(String result) {
                Log.e(TAG, "获得自助机基本信息--------->"+result );
                JSONObject jsonObject = JSONObject.parseObject(result);
                JSONObject json = jsonObject.getJSONObject("serviceBaseInfo");
                BusSelfService bss = JsonForBean.getPerson(json.toString(), BusSelfService.class);
                if (bss != null) {
                    tv_no.setVisibility(View.GONE);
                    iv_mainBg.setVisibility(View.GONE);
                    SpUtils.saveString(YbSelfService.this, SpUtils.STOREID, bss.getStoreId() + "");
                    SpUtils.saveInt(YbSelfService.this, SpUtils.EATIN, bss.getEatIn());
                    SpUtils.saveInt(YbSelfService.this, SpUtils.PACKAGEING, bss.getPackaging());
                    SpUtils.saveInt(YbSelfService.this, SpUtils.ISOFFLINEPAY, bss.getIsOfflinePay());
                    SpUtils.saveInt(YbSelfService.this, SpUtils.ISONLINEPAY, bss.getIsOnlinePay());
                    SpUtils.saveString(YbSelfService.this, SpUtils.PACKING_MONEY,bss.getPackMoney().toString());

                    SpUtils.saveInt(YbSelfService.this, SpUtils.ISALIPAY, bss.getIsAlipay());
                    SpUtils.saveInt(YbSelfService.this, SpUtils.ISWXPAY, bss.getIsWxPay());

                    //是否打印
                    SpUtils.saveInt(YbSelfService.this, SpUtils.ISPRINT, bss.getIsPrint());

                    HashMap mapStoreId = new HashMap();
                    mapStoreId.put("storeId", bss.getStoreId());
                    NetUtils.Post(NetConstants.STORE_BASE_INFO, mapStoreId, new MyCallBack<String>() {
                        @Override
                        public void onSuccess(String result) {
                            Log.e(TAG, "获取店铺信息--------->"+result );
                            JSONObject jsonObject = JSONObject.parseObject(result);
                            JSONObject json = jsonObject.getJSONObject("storeBaseInfo");
                            StoreBean storeBean = JsonForBean.getPerson(json.toString(), StoreBean.class);
                            if (storeBean != null) {
                                SpUtils.saveString(YbSelfService.this, SpUtils.MODELID, storeBean.getModelId() + "");
                                SpUtils.saveString(YbSelfService.this, SpUtils.ADVERTID, storeBean.getAdvertid() + "");
                                SpUtils.saveString(YbSelfService.this, SpUtils.PRINTID, storeBean.getPrintId() + "");
                                SpUtils.saveString(YbSelfService.this, SpUtils.SHOP_NAME, storeBean.getBranchShop() + "");
                                SpUtils.saveString(YbSelfService.this, SpUtils.SHOP_ADDRESS, storeBean.getShopAdress() + "");
                                SpUtils.saveString(YbSelfService.this, SpUtils.SHOP_IMG, storeBean.getShopImg() + "");
                                SpUtils.saveString(YbSelfService.this, SpUtils.EXITPASSWORD, json.getString("deviceEixtPassword"));

                                NetUtils.DownLoadFile(storeBean.getShopImg(), FileConstants.SHOPIMG_CACHE_PATH + "shopimg.jpg", new MyCallBack<File>() {
                                    @Override
                                    public void onSuccess(File result) {
                                        System.out.println("商店图片下载成功");
                                    }

                                    @Override
                                    public void onError(Throwable ex, boolean isOnCallback) {
                                        System.out.println("商店图片下载失败");
                                    }

                                });
                                HashMap mapAd = new HashMap();
                                mapAd.put("advertId", storeBean.getAdvertid() + "");

                                NetUtils.Post(NetConstants.IMAGE_PLAY_LIST, mapAd, new MyCallBack<String>() {
                                    @Override
                                    public void onSuccess(String result) {
                                        Log.e(TAG, "广告信息--------->"+result );
                                        JSONObject jsonObject = JSONObject.parseObject(result);
                                        String  status = jsonObject.getString("status");
                                        if (status.equals("1")){
                                            JSONObject json = jsonObject.getJSONObject("advertBaseInfo");
                                            String playtime = json.getString("playTime");
                                            JSONArray jsonArray = jsonObject.getJSONArray("advertImageList");
                                            System.out.println("jsonArray--" + jsonArray.toString());
                                            String[] strs = new String[jsonArray.size()];
                                            for (int i = 0; i < jsonArray.size(); i++) {
                                                JSONObject object = jsonArray.getJSONObject(i);
                                                strs[i] = object.getString("fileName");
                                                Log.e(TAG, " strs[i]----------》 "+ strs[i] );
                                            }
                                            SpUtils.setSharedPreference("strs",strs);
                                            SpUtils.saveString(APP.getAPP(),"playTime",playtime);
                                        }else {
                                            SpUtils.setSharedPreference("strs",null);
                                        }
                                        ivmain_view_pager.setAdapter(adapter);
                                        ivmain_view_pager.setCurrentItem(0, false);
                                    }
                                });
                            }
                        }
                    });
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {
                super.onError(ex, isOnCallback);
                Log.e(TAG, "onError---------获得自助机基本信息--------->"+ex.getMessage() );
            }
        });


      tip=  getString(R.string.paySuccess);
    }






    // xmpp推送服务
    ServiceManager serviceManager;
    private void startXmpp() {
        serviceManager = new ServiceManager(appContent);
        serviceManager.startService();

    }

    static  String  tip;
    //语音播报
    public static TextToSpeech mTextToSpeech;
    public static void speak(String message){
        SoundControl.getInstance().stopCurrentVolume();
        mTextToSpeech.speak(message, TextToSpeech.QUEUE_ADD,testSpeechMap);
        mTextToSpeech.setOnUtteranceCompletedListener(new TextToSpeech.OnUtteranceCompletedListener() {
            @Override
            public void onUtteranceCompleted(String utteranceId) {
                if (utteranceId.equals("abcdefg")) {
                    SoundControl.getInstance().restartCurrentVolume();
                }
            }
        });

        mTextToSpeech.speak(tip, TextToSpeech.QUEUE_FLUSH, testSpeechMap);
    }



    private OrderBaseInfoBean baseInfoBean = null;
    private JSONArray jsonArray;

    File fileNew;
    private List<OrderGoodsBean> mList = null;

    StringBuffer sb = new StringBuffer();
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            MenuToShow.getInstance().showMenu(this);
        }
        if (onReceicedKeyDown != null && GoodsBasePager.mCurrentPosition == GoodsBasePager.GOODS_PAY_INT) {
            onReceicedKeyDown.OnKeyDown(keyCode, event);
        }
        if(keyCode == KeyEvent.KEYCODE_BACK){
            AppActivityManager.getAppActivityManager().AppExit();
        }
        if (GoodsBasePager.mCurrentPosition != GoodsBasePager.GOODS_PAY_INT){
        Log.e(TAG, "onKeyDown:-----> "+keyCode );
        if (keyCode != 82 && keyCode != 4){
            sb.append((keyCode - 7) + "");
            Log.e(TAG, "sb---->"+sb.toString());
            if (sb.length() == 27) {
                String str=sb.toString().substring(14,sb.toString().length());
                Log.e(TAG, "str---->"+str);
                Map map=new HashMap();
                map.put("orderSernum","busself"+str);

                NetUtils.Post(NetConstants.SCANLEQR, map, new MyCallBack<String>() {
                    @Override
                    public void onSuccess(String result) {

                        JSONObject jsonObject = JSON.parseObject(result);
                        System.out.println("MainLayout---result---->"+result);
                        jsonArray = jsonObject.getJSONArray("goodList");
                        baseInfoBean = JsonForBean.getPerson(jsonObject.getString("busSelfOrder"), OrderBaseInfoBean.class);
                        mList = JsonForBean.getPersonList(jsonArray.toString(), OrderGoodsBean.class);

                        if(mList!=null&&mList.size()>0){

                            String path = FileConstants.CAllNumQR_CACHE_PATH;

                            File file = new File(path);
                            if (file.exists() == false) {
                                file.mkdirs();
                            }
                            String filepath = path + "cash2.jpg";
                            fileNew = new File(filepath);
                            if (fileNew.exists()) {
                                file.delete();
                            }
                            NetUtils.DownLoadFile(baseInfoBean.getOrderCodeUrl(), filepath, new MyCallBack<File>() {
                                @Override
                                public void onSuccess(File result) {

                                    Log.e("下载成功","");
                                    try {
                                        String shopName = SpUtils.getString(YbSelfService.this, SpUtils.SHOP_NAME, "");
                                        String shopAddress = SpUtils.getString(YbSelfService.this, SpUtils.SHOP_ADDRESS, "");
                                        InputStream cashIn = new FileInputStream(fileNew);
//                                        File file = new File(FileConstants.SHOPIMG_CACHE_PATH + "shopimg.jpg");
//                                        InputStream is = new FileInputStream(file);
//                                        YbSelfService.printerUtils.printerShop(mList, shopName, shopAddress, baseInfoBean.getAllMoney() + "",
//                                                cashIn, baseInfoBean.getOrderCallNum(),baseInfoBean.getPackMoney()+"",baseInfoBean.getIsPack());
//
//                                        cashIn.close();
//                                        is.close();
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    super.onError(ex, isOnCallback);
                                    try {
                                        String shopName = SpUtils.getString(YbSelfService.this, SpUtils.SHOP_NAME, "");
                                        String shopAddress = SpUtils.getString(YbSelfService.this, SpUtils.SHOP_ADDRESS, "");

                                        File file = new File(FileConstants.SHOPIMG_CACHE_PATH + "shopimg.jpg");
                                        InputStream is = new FileInputStream(file);
//                                        YbSelfService.printerUtils.printerShop(mList,shopName, shopAddress,
//                                                baseInfoBean.getAllMoney() + "", null, baseInfoBean.getOrderCallNum(),
//                                                baseInfoBean.getPackMoney()+"",baseInfoBean.getIsPack());
//
//                                        is.close();
//                                        Log.e("下载","失败！！！！！");
                                    } catch (Exception e) {
                                        e.printStackTrace();
                                    }
                                }
                            });
                            HashMap map = new HashMap();
                            String sb = SpUtils.getString(APP.getAPP(), SpUtils.DEVICENO, "");
                            map.put("deviceId", sb);
                            map.put("orderId", baseInfoBean.getId() + "");
                            NetUtils.Post(NetConstants.SCANLERETURN, map, new MyCallBack<String>() {
                                @Override
                                public void onSuccess(String result) {
                                    super.onSuccess(result);
                                    Log.e(TAG, "onSuccess:反馈成功!" );
                                }

                                @Override
                                public void onError(Throwable ex, boolean isOnCallback) {
                                    super.onError(ex, isOnCallback);
                                    Log.e(TAG, "onError:反馈失败!");
                                }
                            });
                        }else{
                            System.out.println(mList.size());
                            Toast.makeText(APP.getAPP(),"请重新扫描！",Toast.LENGTH_SHORT).show();
                        }
                    }
                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {
                        Toast.makeText(APP.getAPP(),"请重新扫描",Toast.LENGTH_SHORT).show();
                        System.out.println("MainLayout---result---->"+"失败！！！！！");
                    }
                });
                sb.delete(0, sb.toString().length());
            }
        }}

        return super.onKeyDown(keyCode, event);
    }



    public interface OnToNext {
        void toNext(int position);
    }
    public OnToNext toNextPager;
    public void setToNextPager(OnToNext toNextPager) {
        this.toNextPager = toNextPager;
    }



    public interface OnReceicedKeyDown {
        void OnKeyDown(int keyCode, KeyEvent event);
    }

    public static void setOnReceicedKeyDown(OnReceicedKeyDown onReceicedKeyDown) {
        YbSelfService.onReceicedKeyDown = onReceicedKeyDown;
    }

    public static OnReceicedKeyDown onReceicedKeyDown;




    @Override
    protected void onDestroy() {

        try {
            if(myPayingBroadcast!=null){
                unregisterReceiver(myPayingBroadcast);
            }
            if (serviceManager != null) {
                serviceManager.stopService();
                serviceManager = null;
            }
            if(mTextToSpeech!=null){
                mTextToSpeech.stop();
                mTextToSpeech.shutdown();
            }

            if (myReceiver != null) {
                unregisterReceiver(myReceiver);
            }
            if (mUsbReceiver != null) {
                unregisterReceiver(mUsbReceiver);
            }
            Intent intent = new Intent(this, GpPrintService.class);
            unbindService(conn); // bindService
        } catch (Exception e) {
            e.printStackTrace();
        }
        super.onDestroy();
//        if (PrinterStatusBroadcastReceiver != null) {
//            unregisterReceiver(PrinterStatusBroadcastReceiver);
//        }


        AppActivityManager.getAppActivityManager().finishActivity(this);
    }

    /*
      *  BroadcastReceiver when insert/remove the device USB plug into/from a USB port
      *  创建一个广播接收器接收USB插拔信息：当插入USB插头插到一个USB端口，或从一个USB端口，移除装置的USB插头
      */
    BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            try {
                String action = intent.getAction();
                if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                    if(mUsbDriver.usbAttached(intent))
                    {
                        UsbDevice device = (UsbDevice) intent
                                .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                                || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                                || (device.getProductId() == PID15 && device.getVendorId() == VENDORID))
                        {
                            if(mUsbDriver.openUsbDevice(device))
                            {
                                if(device.getProductId()==PID11)
                                    mUsbDev1 = device;
                                else
                                    mUsbDev2 = device;
                            }
                        }
                    }
                } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                    UsbDevice device = (UsbDevice) intent
                            .getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID15 && device.getVendorId() == VENDORID))
                    {
                        mUsbDriver.closeUsbDevice(device);
                        if(device.getProductId()==PID11)
                            mUsbDev1 = null;
                        else
                            mUsbDev2 = null;
                    }
                } else if (ACTION_USB_PERMISSION.equals(action)) {
                    synchronized (this)
                    {
                        UsbDevice device = (UsbDevice)intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                        if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false))
                        {
                            if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                                    || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                                    || (device.getProductId() == PID15 && device.getVendorId() == VENDORID))
                            {
                                if(mUsbDriver.openUsbDevice(device))
                                {
                                    if(device.getProductId()==PID11)
                                        mUsbDev1 = device;
                                    else
                                        mUsbDev2 = device;
                                }
                            }
                        }
                        else {
                            T.showShort(YbSelfService.this, "permission denied for device");
                        }
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    };

    public static int checkStatus(int iStatus)
    {
        int iRet = -1;
        StringBuilder sMsg = new StringBuilder();
        //0 打印机正常 、1 打印机未连接或未上电、2 打印机和调用库不匹配
        //3 打印头打开 、4 切刀未复位 、5 打印头过热 、6 黑标错误 、7 纸尽 、8 纸将尽
        switch (iStatus) {
            case 0:
                sMsg.append(Constant.Normal_CN);       // 正常
                iRet = 0;
                break;
            case 8:
                sMsg.append(Constant.PaperWillExhausted_CN); // 纸将尽
                iRet = 0;
                break;
            case 3:
                sMsg.append(Constant.PaperWillExhausted_CN); //打印头打开
                break;
            case 4:
                sMsg.append( Constant.CutterNotReset_CN);
                break;
            case 5:
                sMsg.append(Constant.PrintHeadOverheated_CN);
                break;
            case 6:
                sMsg.append(Constant.BlackMarkError_CN);
                break;
            case 7:
                sMsg.append(Constant.PaperExhausted_CN);     // 纸尽==缺纸
                break;
            case 1:
                sMsg.append(Constant.NoConnectedOrNoOnPower_CN);
                break;
            default:
                sMsg.append(Constant.Abnormal_CN);     // 异常
                break;
        }
        return iRet;
    }



    // 检测打印机状态
    public static int getPrinterStatus(UsbDevice mUsbDev1) {
        int iRet = -1;
        byte[] bRead1 = new byte[1];
        byte[] bWrite1 = PrintCmd.GetStatus1();
        if(mUsbDriver.read(bRead1,bWrite1,mUsbDev1)>0)
        {
            iRet = PrintCmd.CheckStatus1(bRead1[0]);
        }

        if(iRet!=0)
            return iRet;

        byte[] bRead2 = new byte[1];
        byte[] bWrite2 = PrintCmd.GetStatus2();
        if(mUsbDriver.read(bRead2,bWrite2,mUsbDev1)>0)
        {
            iRet = PrintCmd.CheckStatus2(bRead2[0]);
        }

        if(iRet!=0)
            return iRet;

        byte[] bRead3 = new byte[1];
        byte[] bWrite3 = PrintCmd.GetStatus3();
        if(mUsbDriver.read(bRead3,bWrite3,mUsbDev1)>0)
        {
            iRet = PrintCmd.CheckStatus3(bRead3[0]);
        }

        if(iRet!=0)
            return iRet;

        byte[] bRead4 = new byte[1];
        byte[] bWrite4 = PrintCmd.GetStatus4();
        if(mUsbDriver.read(bRead4,bWrite4,mUsbDev1)>0)
        {
            iRet = PrintCmd.CheckStatus4(bRead4[0]);
        }
        return iRet;
    }
    private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 国际化标志时间格式类
    // 打印水平制表
    public  static void     printSeatTest(List<OrderGoodsBean> list,UsbDevice mUsbDev1,String shopName,String shopAddress,String AllMoney,String CallNum,String PackMoney,int  isPack,String preMoney,String realMoney) {
        int iStatus = getPrinterStatus(mUsbDev1);
        if(checkStatus(iStatus)!=0)
            return;
        // 小票标题
        mUsbDriver.write(PrintCmd.SetBold(0),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetAlignment(1),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetSizetext(1, 1),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString(shopName, 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintFeedline(1),mUsbDev1); // 打印走纸2行

        mUsbDriver.write(PrintCmd.SetAlignment(1),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetSizetext(0, 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString(shopAddress+"\n"+
//                "请等候叫号，凭票到取货口取货"+"\n"+"---------------------------------", 0),mUsbDev1);
                ""+"\n"+""+"\n"+"---------------------------------", 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetBold(0),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetAlignment(1),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetSizetext(1, 1),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_OrderNumber)+CallNum, 0),mUsbDev1);

        mUsbDriver.write(PrintCmd.SetAlignment(1),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetSizetext(0, 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString("---------------------------------", 0),mUsbDev1);


//        String  ht1 = Utils.stringTo16Hex("商品");
//        String  ht2 = Utils.stringTo16Hex("单价*数量");
//        String   ht3 = Utils.stringTo16Hex("总价");
//
//        String etstring = "10" + "20" +  "00 " + ht1 + "09 " +
//                ht2 + "09 " + ht3 + "0A 0A";
//        byte[] seat = Utils.hexStr2Bytesnoenter(etstring);
//        if (etstring != null && !"".equals(etstring)) {
//            mUsbDriver.write(PrintCmd.SetAlignment(1));
//            mUsbDriver.write(PrintCmd.SetLinespace(40));
//            mUsbDriver.write(PrintCmd.SetHTseat(seat, seat.length),
//                    seat.length,mUsbDev1);
//            mUsbDriver.write(PrintCmd.PrintFeedline(0),mUsbDev1);      // 走纸换行
//        }


        setTransData2(list,"20",mUsbDev1);

        if (isPack==1){
            mUsbDriver.write(PrintCmd.SetAlignment(1),mUsbDev1);
            mUsbDriver.write(PrintCmd.SetSizetext(0, 0),mUsbDev1);
            mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_packingFee)+PackMoney+APP.getAPP().getResources().getString(R.string.print_yuan), 0),mUsbDev1);
        }


        mUsbDriver.write(PrintCmd.SetAlignment(1),mUsbDev1);
        mUsbDriver.write(PrintCmd.SetSizetext(0, 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString("---------------------------------", 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_OrderAmount)+"               "+realMoney+APP.getAPP().getResources().getString(R.string.print_yuan), 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_DiscountedPrice)+"               "+preMoney+APP.getAPP().getResources().getString(R.string.print_yuan), 0),mUsbDev1);

        if (AllMoney.equals("0.0")&&preMoney.length()>3){
            mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_actuallyPaid)+"               "+"0.00"+APP.getAPP().getResources().getString(R.string.print_yuan), 0),mUsbDev1);
        }else {
            mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_actuallyPaid)+"               "+AllMoney+APP.getAPP().getResources().getString(R.string.print_yuan), 0),mUsbDev1);
        }

        mUsbDriver.write(PrintCmd.PrintString("---------------------------------", 0),mUsbDev1);
        mUsbDriver.write(PrintCmd.PrintString(APP.getAPP().getResources().getString(R.string.print_PaymentTime)+sdf.format(new Date()).toString()
                , 1),mUsbDev1);
        setFeedCut(0,mUsbDev1);
    }

    private static void setTransData2(List<OrderGoodsBean> list,String col1,UsbDevice usbDev){
        List<String> mListTab1=new ArrayList<>();
        List<String> mListTab2=new ArrayList<>();

        mListTab1.add(APP.getAPP().getResources().getString(R.string.print_Goods)+"  ");
        mListTab2.add(APP.getAPP().getResources().getString(R.string.print_UnitPriceQquantity)+"");

        for (int i = 0; i < list.size(); i++) {
            int lenth=list.get(i).getName().length();
            if (lenth>7){
                mListTab1.add(list.get(i).getName().substring(0,7));
            }else if (lenth==7){
                mListTab1.add(list.get(i).getName()+"");
            }else if (lenth==6){
                mListTab1.add(list.get(i).getName()+" ");
            }else if (lenth==5){
                mListTab1.add(list.get(i).getName()+"  ");
            }else if (lenth==4){
                mListTab1.add(list.get(i).getName()+"   ");
            }else if (lenth==3){
                mListTab1.add(list.get(i).getName()+"    ");
            }else if (lenth==2){
                mListTab1.add(list.get(i).getName()+"     ");
            }else if (lenth==2){
                mListTab1.add(list.get(i).getName()+"      ");
            }else if (lenth==1){
                mListTab1.add(list.get(i).getName()+"       ");
            }
            mListTab2.add(list.get(i).getPrice()+"*"+list.get(i).getCount());
        }
        String Col1 = Utils.intToHexString(Integer.valueOf(col1), 1)+ " ";// 转换第1列
        for(int i = 0;i<list.size()+1;i++){
            String  ht1 = Utils.stringTo16Hex(mListTab1.get(i));
            String  ht2 = Utils.stringTo16Hex(mListTab2.get(i));
            String etstring = Col1 +   "00 " + ht1 + "09 " +
                    ht2 +  "0A 0A";
            byte[] seat = Utils.hexStr2Bytesnoenter(etstring);
            if (etstring != null && !"".equals(etstring)) {
                mUsbDriver.write(PrintCmd.SetAlignment(1));
                mUsbDriver.write(PrintCmd.SetLinespace(40));
                mUsbDriver.write(PrintCmd.SetHTseat(seat, seat.length),
                        seat.length,usbDev);
                mUsbDriver.write(PrintCmd.PrintFeedline(0),usbDev);      // 走纸换行
            }
        }
    }
    private ArrayList<String> getSeatColHtData(String[] str) {
        ArrayList<String> list = new ArrayList<String>();
        if (str != null) {
            for (int i = 0; i < 6; i++) {
                list.add(str[i]);
            }
        }
        return list;
    }
    // 走纸换行、切纸、清理缓存
    private static void setFeedCut(int iMode,UsbDevice usbDev) {
        mUsbDriver.write(PrintCmd.PrintFeedline(5),usbDev);      // 走纸换行
        mUsbDriver.write(PrintCmd.PrintCutpaper(iMode),usbDev);  // 切纸类型
    }

    private void registerBroadcast() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(GpCom.ACTION_CONNECT_STATUS);
        filter.addAction(GpCom.ACTION_DEVICE_REAL_STATUS);
        this.registerReceiver(PrinterStatusBroadcastReceiver, filter);
    }

    private BroadcastReceiver PrinterStatusBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (GpCom.ACTION_CONNECT_STATUS.equals(intent.getAction())) {
                int type = intent.getIntExtra(GpPrintService.CONNECT_STATUS, 0);
                if (type == GpDevice.STATE_CONNECTING) {
                    Log.e(TAG, "onReceive: "+"----->connecting" );
                } else if (type == GpDevice.STATE_NONE) {
                    Log.e(TAG, "onReceive: "+"后厨wifi打印机未连接" );
                    SpUtils.saveBoolean(context,"wifiPrinter",false);
                    if(MenuToShow.getInstance().blueInterface!=null){
                        MenuToShow.getInstance().blueInterface.BlueListen(false);
                    }
                    mhandler.sendEmptyMessageDelayed(1,100);
                } else if (type == GpDevice.STATE_VALID_PRINTER) {
                    Log.e(TAG, "onReceive: "+"后厨wifi打印机已连接" );
                    Toast.makeText(getApplicationContext(), "后厨wifi打印机已连接！", Toast.LENGTH_SHORT)
                            .show();
                    SpUtils.saveBoolean(context,"wifiPrinter",true);
                    if(MenuToShow.getInstance().blueInterface!=null){
                        MenuToShow.getInstance().blueInterface.BlueListen(true);
                    }
                } else if (type == GpDevice.STATE_INVALID_PRINTER) {
                    Log.e(TAG, "onReceive: "+"----->STATE_INVALID_PRINTER" );
                }
            }
            if (GpCom.ACTION_DEVICE_REAL_STATUS.equals(intent.getAction())) {
                int requestCode = intent.getIntExtra(GpCom.EXTRA_PRINTER_REQUEST_CODE, -1);
                if (requestCode == MAIN_QUERY_PRINTER_STATUS) {
                    int status = intent.getIntExtra(GpCom.EXTRA_PRINTER_REAL_STATUS, 16);
                    String str;
                    if (status == GpCom.STATE_NO_ERR) {
                        str = "打印机正常";
                        SpUtils.saveBoolean(context,"wifiPrinter",true);
                    } else {
                        str = "打印机 ";
                        if ((byte) (status & GpCom.STATE_OFFLINE) > 0) {
                            str += "脱机";
                            SpUtils.saveBoolean(context,"wifiPrinter",false);
                        }
                        if ((byte) (status & GpCom.STATE_PAPER_ERR) > 0) {
                            str += "缺纸";
                        }
                        if ((byte) (status & GpCom.STATE_COVER_OPEN) > 0) {
                            str += "打印机开盖";
                            SpUtils.saveBoolean(context,"wifiPrinter",false);
                        }
                        if ((byte) (status & GpCom.STATE_ERR_OCCURS) > 0) {
                            str += "打印机出错";
                            SpUtils.saveBoolean(context,"wifiPrinter",false);
                        }
                        if ((byte) (status & GpCom.STATE_TIMES_OUT) > 0) {
                            str += "查询超时";
                        }
                    }
                    Log.e(TAG, "str---------------->"+str );
                }

            }

        }
    };
    private void connection() {
        conn = new PrinterServiceConnection();
        Intent intent = new Intent(this, GpPrintService.class);
        bindService(intent, conn, Context.BIND_AUTO_CREATE); // bindService
    }

    class PrinterServiceConnection implements ServiceConnection {
        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.e("ServiceConnection", "onServiceDisconnected() called");
//            mGpService = null;
        }



        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.e("ServiceConnection", "onServiceConnected---------------------------- " );
//            mGpService = GpService.Stub.asInterface(service);
            mhandler.sendEmptyMessageDelayed(1,5000);
        }
    }
    private Handler mhandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what){
                case 1:
//                    try {
//                        String macIp=SpUtils.getString(YbSelfService.this,SpUtils.WIFI_IP,null);
//                        if (macIp!=null){
//                            mGpService.openPort(0, 3, macIp, 9100);
//                        }
//                    } catch (RemoteException e) {
//                        e.printStackTrace();
//                    }

                    break;
            }

        }
    };
    // Get UsbDriver(UsbManager) service
    private boolean printConnStatus() {
        boolean blnRtn = false;
        try {
            if (!mUsbDriver.isConnected()) {
//				UsbManager m_UsbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
                // USB线已经连接
                for (UsbDevice device : mUsbManager.getDeviceList().values()) {
                    if ((device.getProductId() == PID11 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID13 && device.getVendorId() == VENDORID)
                            || (device.getProductId() == PID15 && device.getVendorId() == VENDORID)) {
                        if (!mUsbManager.hasPermission(device)) {
                            break;
                        }
                        blnRtn = mUsbDriver.usbAttached(device);
                        if (blnRtn == false) {
                            break;
                        }
                        blnRtn = mUsbDriver.openUsbDevice(device);
                        // 打开设备
                        if (blnRtn) {
                            if (device.getProductId() == PID11) {
                                mUsbDev1 = device;
                            } else {
                                mUsbDev2 = device;
                            }
                            setClean();// 清理缓存，初始化
                            T.showShort(this, getResources().getString(R.string.SmallTicketPrinterConnected));
                            break;
                        } else {
                            T.showShort(this,  getResources().getString(R.string.SmallTicketPrinterAbnormal));
                            break;
                        }
                    }
                }
            } else {
                blnRtn = true;
            }
        } catch (Exception e) {
            T.showShort(this, e.getMessage());
        }

        return blnRtn;
    }

    // 常规设置
    private void setClean() {
        mUsbDriver.write(PrintCmd.SetClean());// 清除缓存,初始化
    }
}
